package server.rest;

import java.util.HashMap;
import org.apache.commons.lang.StringUtils;
import common.ConfigHelper;

public class OptionsHandler
{
    static String ALLOW_METHOD;
    static String ALLOW_HEADERS;
    static String ALLOW_ORIGIN;
    static String MAX_AGE;

    public OptionsHandler()
    {
        init();
    }
    private void init()
    {
        ALLOW_ORIGIN = ConfigHelper.getStringProperty("server.options.access.control.allow.origin");
        ALLOW_HEADERS = ConfigHelper.getStringProperty("server.options.access.control.allow.methods");
        ALLOW_METHOD = ConfigHelper.getStringProperty("server.options.access.control.allow.headers");
        MAX_AGE = ConfigHelper.getStringProperty("server.options.access.control.max.age");
        
    }
    public HashMap<String, Object> getDefualtOptions(final HttpContext context, final Handler handler)
    {
        context.setHeader("Access-Control-Allow-Origin", ALLOW_ORIGIN);
        String allowMethods = "OPTIONS";
        if (null != handler)
        {
            if (!handler.getHandlerConfig().getAllowOptions().isEmpty())
            {
                allowMethods = StringUtils.join(handler.getHandlerConfig().getAllowOptions(), ",") + "," + allowMethods;
            }
        }
        context.setHeader("Access-Control-Allow-Methods", allowMethods);
        context.setHeader("Access-Control-Allow-Headers", ALLOW_METHOD);
        context.setHeader("Access-Control-Max-Age",MAX_AGE);
        return new HashMap<String,Object>();
    }

    @Rest(method = HttpMethod.OPTIONS, schema = "/options", internal = false)
    public HashMap<String, Object> getOptions(final HttpContext context,final Handler handler)
    {
        context.setHeader("Access-Control-Allow-Origin", ALLOW_ORIGIN);
        String allowMethods = "OPTIONS";
        if (null != handler)
        {
            if (!handler.getHandlerConfig().getAllowOptions().isEmpty())
            {
                allowMethods = StringUtils.join(handler.getHandlerConfig().getAllowOptions(), ",") + "," + allowMethods;
            }
        }
        context.setHeader("Access-Control-Allow-Methods", allowMethods);
        context.setHeader("Access-Control-Allow-Headers", ALLOW_METHOD);
        context.setHeader("Access-Control-Max-Age",MAX_AGE);
        return new HashMap<String,Object>();
    }
}
